package com.heima.search.service.impl;

import com.heima.common.exception.CustException;
import com.heima.common.search.SearchConstants;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/8/10 10:29
 */
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService<SearchArticleVO> esService;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.minio.readPath}")
    String readPath;
    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 1. 参数校验，   校验关键字
        String searchWords = dto.getSearchWords();
        if(StringUtils.isBlank(searchWords)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"搜索的关键字不能为空");
        }
        // 异步记录搜索历史记录
        ApUser user = AppThreadLocalUtils.getUser();
        dto.setUserId(user==null?null:user.getId());
        apUserSearchService.insert(dto);

        if(dto.getMinBehotTime() == null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getPageSize() <= 0){
            dto.setPageSize(10);
        }
        // 2. 构建搜索条件  SearchSourceBuilder\
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //   2.1 基础query条件构建
        //      创建bool条件，用于组合其它基础条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //      bool.must (按照关键词 进行match(分词查询))
        boolQuery.must(QueryBuilders.matchQuery("title",searchWords));
        //      bool.filter(按照最小时间  进行range范围查询)
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        builder.query(boolQuery);
        //   2.2 构建排序条件 按照发布时间降序排序
        builder.sort("publishTime", SortOrder.DESC);
        //   2.3 构建分页条件 按照pageSize
        builder.size(dto.getPageSize());
        //   2.4 构建高亮条件
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
        // 3. 执行搜索，得到结果
        PageResponseResult searchResult = esService.search(builder, SearchArticleVO.class, SearchConstants.APP_ARTICLE_INDEX);
        // 4. 结果 要拼接静态页前缀  图片路径前缀
        List<SearchArticleVO> list = (List<SearchArticleVO>)searchResult.getData();
        for (SearchArticleVO articleVO : list) {
            String images = articleVO.getImages();
            if (StringUtils.isNotBlank(images)) {
                images = Arrays.stream(images.split(","))
                        .map(url -> webSite + url)
                        .collect(Collectors.joining(","));
                articleVO.setImages(images);
            };
            articleVO.setStaticUrl(readPath + articleVO.getStaticUrl());
        }
        return searchResult;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,SearchConstants.APP_ARTICLE_INDEX);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,SearchConstants.APP_ARTICLE_INDEX);
    }
}
